<?php
/*
 * @Author: your name
 * @Date: 2020-12-23 12:01:16
 * @LastEditTime: 2020-12-28 09:59:46
 * @LastEditors: Please set LastEditors
 * @Description: 客户端错误日志
 * @FilePath: /special/application/common/service/platform_manage/log/ClientErrorLogService.php
 */

namespace app\common\service\platform_manage\log;


use app\common\service\BaseService;
use think\Db;

class ClientErrorLogService extends BaseService
{
    /**
     * @name 列表
     * @author wx
     * @date 2020/12/15 9:32
     */
    public function list($params)
    {
        //删除三个月之前的日志
        $this->deleteLog();


        //查询当前用户所属资产组组所管辖的主机id
        $hostIdArr = Db::name('host')->where('group_id', $params['group_id'])->column('id');
        array_push($hostIdArr, 0);

        $field = 'h.name as host_name, h.ip as host_ip, hel.ip,
            hel.id, hel.module, hel.source, hel.error_msg, hel.error_time';

        $db = Db::name('host_error_log hel')
            ->join('host h', 'hel.host_id = h.id', 'left')
            ->field($field)
            ->whereIn('hel.host_id', $hostIdArr)
            ->order('id desc');

        if(!empty($params['data_source'])){
            $db->where('h.name|h.ip|hel.ip', 'like', '%'.$params['data_source'].'%');
        }

        if(!empty($params['module'])){
            $db->where('hel.module', 'like', '%'.$params['module'].'%');
        }

        if(!empty($params['source'])){
            $db->where('hel.source',  $params['source']);
        }

        if(!empty($params['error_msg'])){
            $db->where('hel.error_msg', 'like', '%'.$params['error_msg'].'%');
        }

        if(!empty($params['error_time'])){
            $startTime = strtotime($params['error_time']);
            $db->whereBetween('hel.error_time', [$startTime, $startTime + 86399]);
        }

        $data = $db->order('hel.error_time', 'desc')->paginate()->toArray();

        return $data;
    }

    /**
     * @name 删除三个月之前的日志
     * @author wx
     * @date 2020/12/15 13:52
     */
    private function deleteLog()
    {
        $time = time() - 86400 * 30 * 3;
        Db::name('host_error_log')->where('ctime', '<', $time)->delete();
    }
}